<?php
/*
	Copyright 2006, 2007, 2008, 2009, 2010 Bastiaan Grutters
    
    This file is part of Ages of Strife website.

    Ages of Strife website is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Ages of Strife website is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Ages of Strife website.  If not, see <http://www.gnu.org/licenses/>.
 */
include( '../global/initialize.php' );

$query = "SELECT admin FROM users WHERE user_id = " . $_SESSION[ 'user_id' ];
$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if( isset( $row[ 'admin' ] ) && $row[ 'admin' ] == 1 ) {
	$_SESSION[ 'news_letter_subject' ] = $subject = stripslashes( formatInputLetter( $_POST[ 'subject' ] ) );
	$_SESSION[ 'news_letter_message' ] = $message = stripslashes( formatInputLetter( $_POST[ 'message' ] ) );
	
	if( isset( $_POST[ 'confirm' ] ) && $_POST[ 'confirm' ] == 'confirmed' ) {
		if( isset( $_POST[ 'submit' ] ) && $_POST[ 'submit' ] == 'Test' ) {
			$add_where = " AND admin = 1";
			$status = "Sent a test newsletter to all game admins";
			$message = "*** Test newsletter (the real message starts below this) ***\r\n\r\n" . $message;
		}
		else {
			$add_where = "";
			$status = "Sent the newsletter to all subscribers";
		}
		
	    $query = "SELECT email " .
	    		"FROM users " .
	    		"WHERE news_letter = 1 AND email != ''$add_where";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$num = mysql_numrows( $result );
		if( $num > 0 ) {
			$failed = $success = 0;
			$header = 	'From: newsletter@agesofstrife.com' . "\r\n" .
	    				'Reply-To: newsletter@agesofstrife.com' . "\r\n" .
	   					'X-Mailer: PHP/' . phpversion();
			while( $i < $num ) {
				if( mail( mysql_result( $result, $i, 'email' ), $subject, html_entity_decode( $message ), $header ) ) {
					$success ++;
				}
				else {
					$failed ++;
				}
				$i ++;
			}
			$status .= " (Sent successfully: $success, failed: $failed)";
		}
		else {
			$status = "There is noone to send the newsletter to!";
		}
	}
	else {
		$status = "Nothing sent, but message saved in session.";
	}
	
	$_SESSION[ 'newsletter_send_status' ] = $status;
	header( "Location: send_newsletter.php" );
}
else {
	$_SESSION[ 'admin' ] = 0;
	header( "Location: ../overview/overview.php" );
}
?>
